﻿using Edu.Common.Win32;
using MainApp.Utils;
using System;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;

namespace MainApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private IntPtr _hwnd;
        private WindowState _oldState;
        /// <summary>
        /// 获取当前窗口是否为后台窗口
        /// </summary>
        private bool _isBackgroundWindow = false;

        private TrayIconTool _TrayIconTool;

        private KeepTopMostTool _keepTopMostTool;

        /// <summary>
        /// 获取或设置是否允许强制关闭窗口
        /// </summary>
        public bool ForceClose { get; set; }

        /// <summary>
        /// 当前的窗口句柄
        /// </summary>
        public IntPtr Hwnd { get { return _hwnd; } }

        public MainWindow()
        {
            InitializeComponent();

            SourceInitialized += MainWindow_SourceInitialized;
            Loaded += MainWindow_Loaded;
            Closing += MainWindow_Closing;
            Closed += MainWindow_Closed;

            Tools.SetAutoRun();
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (ForceClose)
            {
                _TrayIconTool?.Close();
                return;
            }
            e.Cancel = true;
        }

        private void MainWindow_Closed(object sender, EventArgs e)
        {
            _keepTopMostTool?.Dispose();
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            _oldState = WindowState;

            OnConverDesktopChanged();

            //try { _TrayIconTool = new TrayIconTool(this); } catch { }

            //显示图标窗口
            var iconWindow = new IconWindow() { Owner = this };
            iconWindow.Show();

            Task.Run(() =>
            {
                //启动文件
                var runFile = AppConfig.Current.RunFilePath;
                PPTTools.RunPPTFile(runFile);
            });

            ////启动计时器
            //StartTimer();
        }

        private void MainWindow_SourceInitialized(object sender, EventArgs e)
        {
            var source = (HwndSource)HwndSource.FromVisual(this);
            _hwnd = source.Handle;
            //source.AddHook(HwndSourceHook);
            var keepTopMostTool = new KeepTopMostTool(_hwnd, 500);
            _keepTopMostTool = keepTopMostTool;
            keepTopMostTool.StartKeepTopmost();
            HideAltTab();
        }

        /// <summary>
        /// 设置alt+tab中隐藏显示
        /// </summary>
        private void HideAltTab()
        {
            try
            {
                var exStyle = ClrMethods.GetWindowStylesEx(_hwnd);
                exStyle |= Edu.Common.Win32.Enums.WindowStylesEx.WS_EX_TOOLWINDOW;
                ClrMethods.SetWindowStylesEx(_hwnd, exStyle);
            }
            catch { }
        }

        /// <summary>
        /// HOOK窗口消息
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="msg"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <param name="handled"></param>
        /// <returns></returns>
        private IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            var WM_ACTIVATE = 0x0006;//此消息将发送给当前激活或失去激活的窗体
            //var WM_ACTIVATEAPP = 0x001C;//此消息将发送给进程的所有窗体
            if (msg == WM_ACTIVATE)
            {
                //wParam为0表示失去激活状态，lParam为IntPtr.Zero表示当前进程失去焦点
                _isBackgroundWindow = wParam.ToInt32() == 0 && lParam == IntPtr.Zero;
            }
            return IntPtr.Zero;
        }

        /// <summary>
        /// 激活或隐藏窗口
        /// </summary>
        /// <param name="autoHidden">标识是否自动切换窗口到隐藏状态</param>
        public void ActiveOrDeactiveWindow(bool autoHidden = true)
        {
            Tools.ShowSettingsWindow();
            //ActiveOrDeactiveWindow(out WindowState _, autoHidden: autoHidden);
        }

        /// <summary>
        /// 激活或隐藏窗口
        /// </summary>
        /// <param name="oldState">旧的窗口状态</param>
        /// <param name="autoHidden">标识是否自动切换窗口到隐藏状态</param>
        private void ActiveOrDeactiveWindow(out WindowState oldState, bool autoHidden = true)
        {
            oldState = WindowState.Normal;
            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(() => ActiveOrDeactiveWindow(autoHidden: autoHidden));
                return;
            }
            oldState = WindowState;
            if (ShowInTaskbar)
            {
                if (WindowState == WindowState.Minimized || _isBackgroundWindow)
                {
                    var foregoundHwnd = User32.GetForegroundWindow();
                    if (foregoundHwnd == Hwnd)
                        return;
                    if (WindowState == WindowState.Minimized)
                        WindowState = _oldState;
                    Tools.ForegroundWindow(Hwnd);
                    return;
                }
                if (autoHidden)
                    HiddenWindow();
                return;
            }
            ShowInTaskbar = true;
            WindowState = WindowState.Normal;
            Tools.ForegroundWindow(Hwnd);
        }

        /// <summary>
        /// 隐藏窗口
        /// </summary>
        private void HiddenWindow()
        {
            WindowState = WindowState.Minimized;
            ShowInTaskbar = false;
        }

        /// <summary>
        /// 遮挡桌面状态变化时处理
        /// </summary>
        public void OnConverDesktopChanged()
        {
            OnConverDesktopChanged(null);
        }

        /// <summary>
        /// 遮挡桌面状态变化时处理
        /// </summary>
        /// <param name="coverDesktop"></param>
        public void OnConverDesktopChanged(bool? coverDesktop)
        {
            var coverDesktopValue = coverDesktop ?? AppConfig.Current.CoverDesktop;
            IsHitTestVisible = coverDesktopValue;
            Background = new SolidColorBrush(coverDesktopValue ? Color.FromArgb(1, 255, 255, 255) : Colors.Transparent);
        }

        private void btnMainButton_Click(object sender, RoutedEventArgs e)
        {
            PPTTools.SlideToNext();
        }
    }
}
